<template>
  <!--规则剔除  新增/修改-->
  <section class="component modify-role">
    <el-form :model="addModel" :rules="rules" ref="form" label-width="90px" class="tableInput">
      <el-row>
        <el-col :span="19" class="fontMargin">
          基本信息:
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="策略代码" prop="strategyNo">
            <el-input v-model.trim="addModel.strategyNo" :disabled="disabled" :maxlength="20"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="策略名称" prop="strategyName">
            <el-input v-model.trim="addModel.strategyName" :disabled="disabled" :maxlength="20"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="策略状态" prop="state">
            <el-select v-model="addModel.state" :disabled="disabled">
              <el-option v-for="{ index, name, code } in $dict.getDictData(
                  'CommonState'
                )" :key="index" :label="name" :value="code"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="优先级" prop="strategyPriority">
            <el-input v-model.trim="addModel.strategyPriority" :disabled="disabled" :maxlength="4"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="19" class="fontMargin">
          设置剔除渠道:
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="剔除渠道" align="left" prop="channel">
            <el-select v-model="addModel.channel" :disabled="disabled">
              <el-option v-for="{ index, name, code } in $dict.getDictData(
                  'ChannelType'
                )" :key="index" :label="name" :value="code"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="有效日期">
            <el-date-picker v-model="addModel.expiryDate" type="datetime" placeholder="选择日期" default-time="23:59:59" :disabled="disabled">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="剔除类型" align="left" prop="strategyEliminateType">
            <el-select v-model="addModel.strategyEliminateType" :disabled="disabled||channelDisabled || disStrategyEliminateType" @change="onchange">
              <el-option v-for="{ index, name, code } in $dict.getDictData(
                  'StrategyEliminateType'
                )" :key="index" :label="name" :value="code"></el-option>
            </el-select>
            <el-button style="margin-left:20px" @click="updata" :disabled="disabled || disStrategyEliminateType">添加</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <from-base v-model="channelJsons" :showIn="showIn" :deleDisbled="disabled" class="widthMargin" :flag="false"></from-base>
      <el-row>
        <el-col :span="19" class="fontMargin">
          剔除策略参数设置:
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-card class="cardStyle">
            <div slot="header" class="row between-span">
              <span>设置获取数据规则</span>
              <el-button @click="addNewConfigLine" :disabled="disabled">增加</el-button>
            </div>
            <expression-base v-model="strategyDataSet" :flag="false" :disabledData="disabled"></expression-base>
          </el-card>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item label="策略注记" label-width="85px" prop="remark">
          <el-col class="widthOne">
            <el-input type="textarea" v-model="addModel.remark" :rows="3" :maxlength="300" :disabled="disabled" show-word-limit></el-input>
          </el-col>
        </el-form-item>
      </el-row>
      <el-row v-if="showRke">
        <el-row v-if="!history">
          <el-row class="widthMarginTwo">队列历史注记</el-row>
          <el-col class="widthMarginThree">
            <data-box :data="QueueHistory" :page="pageService">
              <template slot="columns">
                <el-table-column prop="createTime" label="注记时间" :min-width="$helper.getColumnWidth(5)" :formatter="row => $filter.dateTimeFormat(row.createTime)" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="operatorRealName" label="添加人" :min-width="$helper.getColumnWidth(5)" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="remark" label="内容" :min-width="$helper.getColumnWidth(5)" show-overflow-tooltip>
                </el-table-column>
              </template>
            </data-box>
          </el-col>
        </el-row>
        <el-row v-else>
          <el-col>
            <el-form-item label="申请人">
              {{ addModel.operatorRealName}}
            </el-form-item>
          </el-col>
          <el-col class="widthMarginFour">审批历史</el-col>
          <el-col class="widthTwo">
            <data-box :data="approvalHistory">
              <template slot="columns">
                <el-table-column prop="approvalRealName" label="审批人" :min-width="$helper.getColumnWidth(5)" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="approvalTime" label="审批时间" :formatter="row => $filter.dateTimeFormat(row.approvalTime)" :min-width="$helper.getColumnWidth(5)" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="applyStatus" label="审批结果" :formatter="
                    row => $filter.dictConvert(row.applyStatus, 'ApplyStatus')
                  " :min-width="$helper.getColumnWidth(5)" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="approvalOpinion" label="审批意见" :min-width="$helper.getColumnWidth(5)" show-overflow-tooltip>
                </el-table-column>
              </template>
            </data-box>
          </el-col>
        </el-row>
      </el-row>
    </el-form>
    <div class="operate-buttons" v-if="disabled">
      <el-button @click="close">关闭</el-button>
    </div>
    <div class="operate-buttons" v-else>
      <el-button @click="close">取消</el-button>
      <el-button @click="commit">{{`${operationType.DEFAULT==='OPERATION_EDIT'?'提交审批':'保存'}`}}</el-button>
    </div>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Dependencies } from "~/core/decorator";
import { State, Getter, Action } from "vuex-class";
import { RuleRemovedService } from "~/services/domain-service/rule-removed.service";
import FromBase from "./from-base.vue";
import { Emit, Prop, Watch } from "vue-property-decorator";
import ExpressionBase from "./expression-base.vue";
import { PageService } from "~/utils/page.service";
import { IstrategyInfo, FormItem } from "~/components/system-manage/strategy-config/strategy-helper.config";
import { OPERATION_TYPE } from "~/config/enum.config";
import { ValidatorService } from "~/utils/validator.service";
import { CaseApplyRecordService } from "~/services/domain-service/case-apply-record.service";

@Component({
  components: { FromBase, ExpressionBase }
})
export default class AddRule extends Vue {
  @Dependencies(PageService)
  private pageService: PageService;
  @Dependencies(RuleRemovedService)
  private ruleRemovedService: RuleRemovedService;
  @Dependencies(CaseApplyRecordService)
  private caseApplyRecordService: CaseApplyRecordService;

  @Prop({ type: Object })
  private roleData: any;
  private addModel: any = {
    strategyNo: '',
    strategyName: '',
    state: '',
    strategyPriority: '',
    channel: "",
    expiryDate: "",
    strategyEliminateType: '',
    formulaJson: '[]',
    remark: ''
  };
  // 页面按钮类型
  private operationType: any = OPERATION_TYPE
  private showIn = true;
  private showRke = true;
  private history = false;
  private approvalHistory: any = [];
  private QueueHistory: any = []
  private disabled = false;
  private verification: boolean = false
  private channelDisabled: boolean = false
  private disStrategyEliminateType: boolean = false
  private channelJsons: any = [];
  private counter: number = 0
  private rules: any = {
    strategyNo: [
      { required: true, message: "请输入策略代码", trigger: "blur" },
      {pattern:this.$validator.regex.numAndEn,message:'请输入非中文'}
    ], 
    strategyName: [
      { required: true, message: "请输入策略名称", trigger: "blur" }
    ],
    strategyPriority: [
      { required: true, message: "请输入优先级", trigger: "blur" }
    ],
    state: [
      { required: true, message: "请选择策略状态", trigger: "change" }
    ],
    remark: [{ required: true, message: "请填写策略注记", trigger: "blur" }]
  };
  @Emit("refreshList")
  public refreshList() { }
  @Emit("close")
  public close() { this.counter = 0 }
  /**
   * 剔除类型监听
   */
  private onchange(v) {
    v ? this.$set(this.addModel, 'strategyEliminateType', v) : this.$set(this.addModel, 'strategyEliminateType', '')
  }
  /**
   * 剔除渠道和剔除类型联动
   */
  @Watch('addModel.channel')
  private change(v) {
    if (!v) return
    const channelList = ['ALL','SELF', 'OUTER', 'LAWSUIT', 'ROBOT']
    const item = channelList.find(f => f === v)
    this.onchange(!!item)
    if (item) {
      this.channelDisabled = true
      this.addModel.strategyEliminateType = 'AUTO_ELIMINATE'
    } else {
      this.channelDisabled = false
      // this.$set(this.addModel, 'strategyEliminateType', '')
    }
  }

  private get strategyDataSet() {
    if (!this.addModel.formulaJson) return [];
    return JSON.parse(this.addModel.formulaJson) as IstrategyInfo[];
  }

  private set strategyDataSet(value) {
    this.addModel.formulaJson = JSON.stringify(value);
  }
  private updata() {
    const channel = this.addModel.channel;
    const expiry = this.addModel.expiryDate;
    const strategyEliminateType = this.addModel.strategyEliminateType
    if (!channel || !expiry || !strategyEliminateType) {
      this.$message.warning("请完善剔除渠道相关条件设置！");
      return false;
    } else {
      this.channelJsons.push({
        id: this.counter++,
        channel: this.addModel.channel,
        expiryDate: this.addModel.expiryDate,
        strategyEliminateType: this.addModel.strategyEliminateType
      });
      this.addModel.channel = "";
      this.channelDisabled = false;
      this.addModel.expiryDate = "";
      this.$set(this.addModel, 'strategyEliminateType', '')
    }
  }
  private reset() {
    const from: any = this.$refs["form"];
    from.resetFields();
    this.channelDisabled = false
    this.operationType.DEFAULT === 'OPERATION_SEE' ? this.disabled = true : this.disabled = false
    // 页面初始化为新增时
    if (this.operationType.DEFAULT === 'OPERATION_ADD') {
      this.addModel = {
        strategyNo: '',
        strategyName: '',
        state: 'ENABLED',
        strategyPriority: '',
        channel: "",
        expiryDate: "",
        strategyEliminateType: '',
        formulaJson: '[]',
        remark: ''
      };
      this.channelJsons = [];
      this.showRke = false
    } else {
      this.addModel = this.roleData;
      this.addModel.channel = "";
      this.channelJsons = JSON.parse(this.roleData.channelJson);
      this.showRke = true
    }
    if (this.addModel.id) {
      const id = { id: this.addModel.id };
      // 队列历史注记
      if (this.operationType.DEFAULT === 'OPERATION_EDIT' || this.operationType.DEFAULT === 'OPERATION_SEE') { this.ruleHistoryNotes(id) }
      // 审批历史
      (this.operationType.DEFAULT === 'APPROVAL_LOG') ? this.ruleApproval(id) : this.history = false;
    }
  }

  /**
   * 提交验证并并与数据库交互
   */
  private commit() {
    this.addModel.channelJson = JSON.stringify(this.channelJsons);
    this.strategyDataSet.map(v => {
      v.value = (typeof v.value === 'string') ? v.value : v.value + ''
    })
    this.addModel.formulaJson = JSON.stringify(this.strategyDataSet);
    const Form: any = this.$refs["form"];
    Form.validate(valid => {
      if (!valid) return;
      if (this.addModel.channelJson.length === 2) {
        this.$message.error('请完善剔除渠道设置!')
      } else if (this.addModel.formulaJson.length === 2) {
        this.$message.error('请设置数据规则!')
      }
      else {
        this.validateExpression()
        this.verificationBrackets()
        setTimeout(() => {
          if (this.verification) {
            this.operationType.DEFAULT === 'OPERATION_ADD' ? this.addRule() : this.updateRule();
          }
        }, 500)
      }
    });
  }

  /**
   * 新增剔除策略
   */
  private addRule(): boolean {
    this.ruleRemovedService.saveRule(this.addModel).subscribe(data => {
      this.$message.success("新增成功!");
      this.channelJsons = [];
      this.refreshList();
      this.close();
    });
    return true;
  }

  /**
   * 修改剔除策略
   */
  private updateRule(): boolean {
    this.ruleRemovedService.updateRule(this.addModel).subscribe(data => {
      this.$message.success("修改成功!");
      this.refreshList();
      this.close();
    });
    return true;
  }

  /**
   * 队列历史注记
   */
  private ruleHistoryNotes(id) {
    this.ruleRemovedService
      .queryRuleLogList(id, this.pageService)
      .subscribe(data => {
        this.QueueHistory = data;
      });
  }
  /**
   * 审批历史
   */
  private ruleApproval(id) {
    this.history = true;
    this.disabled = true;
    this.addModel.state === "PENDING" ? (this.approvalHistory = []) : this.caseApplyRecordService
      .recordHistoryByTaskId({ caseTaskId: id.id, applyCategory: 'RULE_ELIMINATE' })
      .subscribe(data => {
        this.approvalHistory = data;
      });
  }
  private addNewConfigLine() {
    let addFlag = true;
    if (this.strategyDataSet.length >= 5) {
      this.$message.warning('数据规则已达最大长度!')
      return
    }
    if (this.strategyDataSet.length) {
      const lastLine = this.strategyDataSet[this.strategyDataSet.length - 1];
      addFlag = !!lastLine.relation && !!lastLine.variable && !!lastLine.symbol && !!lastLine.value;
    }
    if (addFlag) {
      this.strategyDataSet.push({
        relation: "",
        variable: "",
        symbol: "",
        leftBracket: "",
        rightBracket: "",
        value: ""
      });
    } else {
      this.validateExpression()
    }
  }
  /**
   * 验证数据括号
   */
  private verificationBrackets() {
    let numLeft = 0
    let numRight = 0
    let numsLeft = 0
    let numsRight = 0
    const formula = JSON.parse(this.addModel.formulaJson).map(v => {
      switch (v.leftBracket) {
        case '(':
          numLeft += 1
          break;
        case '((':
          numsLeft += 1
          break;
      }
      switch (v.rightBracket) {
        case ')':
          numRight += 1
          break;
        case '))':
          numsRight += 1
          break;
      }
    })
    if (numLeft !== numRight || numsLeft !== numsRight) { 
       this.$message.error('请检查括号的完整性!'); 
       return
      }

  }


  /**
   * 验证数据是否完整
   */
  private validateExpression() {
    const rules = {
      relation: { required: true, message: "请选择链接关系符" },
      variable: { required: true, message: "请选择字段" },
      symbol: { required: true, message: "请选择操作符" },
      value: { required: true, message: "缺少期望值" }
    };
    const results = this.strategyDataSet.map(v =>
      ValidatorService.validate(v, rules)
    );
    return Promise.all(results)
      .then(() => {
        this.verification = true;
        return true
      })
      .catch(({ errors }) => {
        if (errors.length) this.$message(errors[0].message);
        this.verification = false;
        return Promise.reject(false);
      });
  }

}
</script>

<style lang="less" scoped>
.widthMargin {
  width: 715px !important;
  margin-left: 88px !important;
}
.fontMargin {
  font-weight: bold !important;
  margin-left: 25px !important;
}
.cardStyle {
  margin-top: 20px !important;
  width: 718px !important;
  margin-left: 85px !important;
  box-shadow: none !important;
  border-bottom: 1px solid #ebeef5 !important;
}
.widthOne {
  width: 720px !important;
}
.widthTwo {
  width: 740px !important;
}
.widthMarginTwo {
  width: 180px !important;
  margin-left: 25px !important;
}
.widthMarginThree {
  width: 740px !important;
  margin-left: 75px !important;
}
.widthMarginFour {
  width: 75px !important;
  text-align: right !important;
}
</style>
